<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElButton, ElMessageBox } from "element-plus";
import { useRoute } from "vue-router";
import { getClusterGroupConfigsApi, setClusterGroupConfigsApi } from '@/api/configs/clusterConfig';
const configGroupName = "mqtt";

// 定义MQTT配置类型
interface MqttBrokerConfig {
  serviceName: string; // MQTT服务名 (emqx, mochi)
  internalIp: string; // 内网IP
  externalIp: string; // 公网IP
  tcpPort: number; // TCP端口
  wsPort: number; // WebSocket端口
  username: string; // 用户名
  password: string; // 密码
}

const route = useRoute();
const formRef = ref<InstanceType<typeof ElForm>>();

// 初始化表单数据
const formData = reactive<{
  clusterId: number;
  groupName: string;
  config: MqttBrokerConfig;
  updatedAt: string;
}>({
  clusterId: 0,
  groupName: configGroupName,
  config: {
    serviceName: '',
    internalIp: '',
    externalIp: '',
    tcpPort: 0,
    wsPort: 0,
    username: '',
    password: ''
  },
  updatedAt: ''
});

// MQTT服务名选项
const serviceOptions = [
  { label: 'emqx', value: 'emqx' },
  { label: 'mochi', value: 'mochi' }
];

// 表单验证规则
const rules = reactive<Record<string, any>>({
  'config.serviceName': [
    { required: true, message: '请选择MQTT服务名', trigger: 'change' }
  ],
  'config.internalIp': [
    { required: true, message: '请输入内网IP', trigger: 'blur' },
    { pattern: /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/, message: '请输入有效的IP地址', trigger: 'blur' }
  ],
  'config.tcpPort': [
    { required: true, message: '请输入TCP端口', trigger: 'blur' },
    { type: 'number', min: 1, max: 65535, message: '端口范围应在1-65535之间', trigger: 'blur' }
  ],
  'config.username': [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  'config.password': [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
});

// 初始化数据
onMounted(() => {
  const clusterId = route.query.clusterId;
  if (clusterId) {
    formData.clusterId = Number(clusterId);
    // 获取MQTT配置
    getClusterGroupConfigsApi({
      clusterId: formData.clusterId,
      groupName: formData.groupName
    }).then(res => {
      if (res.code === 0 && res.data?.configs) {
        formData.updatedAt = res.data.updatedAt || '';
        try {
          const configMap: Record<string, string> = {};
          res.data.configs.forEach(item => {
            configMap[item.configKey] = item.configValue;
          });

          // 填充表单数据
          formData.config = {
            serviceName: configMap.serviceName || '',
            internalIp: configMap.internalIp || '',
            externalIp: configMap.externalIp || '',
            tcpPort: configMap.tcpPort ? Number(configMap.tcpPort) : 0,
            wsPort: configMap.wsPort ? Number(configMap.wsPort) : 0,
            username: configMap.username || '',
            password: configMap.password || ''
          };
        } catch (e) {
          console.error('解析MQTT配置数据失败', e);
        }
      }
    });
  }
});

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
    const submitData = {
      clusterId: formData.clusterId,
      groupName: formData.groupName,
      configs: [
        { configKey: 'serviceName', configValue: formData.config.serviceName, configDesc: 'MQTT服务名' },
        { configKey: 'internalIp', configValue: formData.config.internalIp, configDesc: '内网IP' },
        { configKey: 'externalIp', configValue: formData.config.externalIp, configDesc: '公网IP' },
        { configKey: 'tcpPort', configValue: formData.config.tcpPort.toString(), configDesc: 'TCP端口' },
        { configKey: 'wsPort', configValue: formData.config.wsPort.toString(), configDesc: 'WebSocket端口' },
        { configKey: 'username', configValue: formData.config.username, configDesc: '用户名' },
        { configKey: 'password', configValue: formData.config.password, configDesc: '密码' }
      ]
    };

    ElMessageBox.confirm(
      '确定要保存私有MQTT服务器配置吗？',
      '确认提交',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    ).then(async () => {
      await setClusterGroupConfigsApi(submitData);
      ElMessage.success('保存成功');
    }).catch(() => ElMessage.info('已取消保存'));
  } catch (error) {
    ElMessage.error('表单验证失败，请检查填写内容');
  }
};

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields();
};
</script>

<template>
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="160px" class="form-container">
    <el-form-item label="MQTT服务名" prop="config.serviceName">
      <el-select v-model="formData.config.serviceName" placeholder="请选择MQTT服务名">
        <el-option v-for="option in serviceOptions" :key="option.value" :label="option.label" :value="option.value" />
      </el-select>
    </el-form-item>

    <el-form-item label="内网IP" prop="config.internalIp">
      <el-input v-model="formData.config.internalIp" placeholder="请输入内网IP" />
    </el-form-item>

    <el-form-item label="公网IP" prop="config.externalIp">
      <el-input v-model="formData.config.externalIp" placeholder="请输入公网IP（可选）" />
    </el-form-item>

    <el-form-item label="TCP端口" prop="config.tcpPort">
      <el-input v-model.number="formData.config.tcpPort" placeholder="请输入TCP端口" type="number" />
    </el-form-item>

    <el-form-item label="WebSocket端口" prop="config.wsPort">
      <el-input v-model.number="formData.config.wsPort" placeholder="请输入WebSocket端口（可选）" type="number" />
    </el-form-item>

    <el-form-item label="用户名" prop="config.username">
      <el-input v-model="formData.config.username" placeholder="请输入用户名" />
    </el-form-item>

    <el-form-item label="密码" prop="config.password">
      <el-input v-model="formData.config.password" placeholder="请输入密码" type="password" />
    </el-form-item>

    <!-- 更新时间显示 -->
    <el-form-item label="更新时间" >
      <el-input v-model="formData.updatedAt" disabled placeholder="暂无更新时间" />
    </el-form-item>

    <el-form-item class="form-actions">
      <el-button type="primary" @click="submitForm">提交</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">
.form-container { max-width: 800px; margin: 20px auto; padding: 20px; }
.form-actions { display: flex; justify-content: center; gap: 10px; margin-top: 30px; }
</style>
